using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using UnityEngine.SceneManagement;
public class SceneTransition : MonoBehaviour
{
    [SerializeField] private Image transitionImage;
    
    
    //
    private void Start()
    {
        // 永不销毁
        GameObject.DontDestroyOnLoad(this.gameObject);
        // 添加事件
        EventCenter.Instance.AddEventListener<int>(EventName.EVENT_SCENE_SCENESWITE, LoadScene);
    }

    public void LoadScene(int sceneIndex)
    {
        StartCoroutine(Load(sceneIndex));
    }

    //
    IEnumerator Load(int sceneIndex)
    {
        // animator.Play("Scene_FadeOut");
        // 淡出动画，透明度从0-1
        transitionImage.DOFade(1.0f, 2.0f);
        // 一秒后返回
        // 加载新场景，原场景数据保存
        EventCenter.Instance.EventTrigger(EventName.EVENT_SAVEDATA_NEXTLEVEL);
        // 播放音效
        AudioManager.Instance.PlayAudioSourceSFX(AudioSFXPath.PROP_NEXTLEVEL, this.gameObject);
        yield return new WaitForSeconds(2.0f);

        // 
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneIndex);
        asyncOperation.completed += AfterLoadScene;
    }

    private void AfterLoadScene(AsyncOperation operation)
    {
        // animator.Play("Scene_FadeIn");
        // 淡入动画，透明度从1-0
        transitionImage.DOFade(0f, 2.0f);
        // 加载完新关卡，存档，保存玩家数据
        EventCenter.Instance.EventTrigger(EventName.EVENT_SAVEDATA_LOADNEWSCENE);
        // 播放音效
        AudioManager.Instance.PlayAudioSourceSFX(AudioSFXPath.PROP_LOADSCENE, this.gameObject);
    }
    
}
